﻿// JScript File






function ShowMessage(message)
{
    SetUnBlur();
    alert(message);
    UnSetUnBlur();
}

function Confirm(message)
{
    SetUnBlur();
    var result = window.confirm(message);
    UnSetUnBlur();
    
    return result;
}


// DICTIONARY //

function Lookup(key) 
{
  return(this[key]);
}

function Delete() 
{
  for (c=0; c < Delete.arguments.length; c++) 
  {
    this[Delete.arguments[c]] = null;
  }
  // Adjust the keys (not terribly efficient)
  var keys = new Array()
  for (var i=0; i<this.Keys.length; i++)
  {
    if(this[this.Keys[i]] != null)
      keys[keys.length] = this.Keys[i];
  }
  this.Keys = keys;
}

function Add() 
{
  for (c=0; c < Add.arguments.length; c+=2) 
  {
    // Add the property
    this[Add.arguments[c]] = Add.arguments[c+1];
    // And add it to the keys array
    this.Keys[this.Keys.length] = Add.arguments[c];
  }
}

function Dictionary() 
{
  this.Add = Add;
  this.Lookup = Lookup;
  this.Delete = Delete;
  this.Keys = new Array();
}

var styles = new Dictionary();


//xml->html
function TransformNode(node, path)
{   
   
    
    var style;
    
    if (styles.Lookup(path) == null)
    {      
        style = isMozilla ? GetStyleInMozilla(path) : GetStyleInIE(path);        
        styles.Add(path, style);        
    }
    else    
    {   
        style = styles.Lookup(path);
    }
     
    var transformedNode;
    try
    {        
        transformedNode = isMozilla ? TransformNodeInMozilla(node, style) : TransformNodeInIE(node, style);     
    }
    catch (e)
    {  // значит была запомнена null-евая версия полученная в результате сбоя сети.
     
        style = isMozilla ? GetStyleInMozilla(path) : GetStyleInIE(path);        
        
        styles.Delete(path);   // удаляем её
        styles.Add(path, style);   // и запоминаем свежую
        
        transformedNode = isMozilla ? TransformNodeInMozilla(node, style) : TransformNodeInIE(node, style);
    }
    
    return transformedNode;
}

function GetStyleInIE(path)
{
    style = CreateXmlDOM();
    style.async = false;
    style.load(path);
    return style;
}

function GetStyleInMozilla(path)
{  
    var xslStylesheet; 
    // load the xslt file, example1.xsl 
    var myXMLHTTPRequest = new XMLHttpRequest(); 
    myXMLHTTPRequest.open("GET", path, false); 
    myXMLHTTPRequest.send(null); 

    // get the XML document and import it 
    xslStylesheet = myXMLHTTPRequest.responseXML; 

    return xslStylesheet; 
}

function TransformNodeInIE(node, style)
{
    return node.transformNode(style);
}

function TransformNodeInMozilla(node, style)
{
    var xsltProcessor = new XSLTProcessor(); 
    xsltProcessor.importStylesheet(style); 
    
    var resultDocument = xsltProcessor.transformToDocument(node);

    return SerializeXmlNode(resultDocument);
}    


function SerializeXmlNode(xmlNode)
{
    if (isMozilla)
    {        
        var serializer = new XMLSerializer();
        var xml = serializer.serializeToString(xmlNode);
        return xml.replace("<?xml version=\"1.0\" encoding=\"UTF-8\"?>", "<?xml version=\"1.0\" ?>");
    }
    else 
        return xmlNode.xml;
}


function AddSectionsItemToArray(array, sectionXml)        
{
    var navModexPath = "/assessmentTest/testPart/@navigationMode";
    var navigationMode = isMozilla ? appPointer.xmlSource.evaluate(navModexPath, appPointer.xmlSource, null, 9, null).singleNodeValue : appPointer.xmlSource.selectSingleNode(navModexPath);
            

    var sectionPartsXml = GetDirectChildNodes(sectionXml, "assessmentSection");
    for (var i = 0; i < sectionPartsXml.length; i++)
        AddSectionsItemToArray(array, sectionPartsXml[i]);        
        
    
    var itemsXml = GetDirectChildNodes(sectionXml, "assessmentItem");
    
    for (var i = 0; i < itemsXml.length; i++)
    {
        var item = new Item(itemsXml[i]);
        
        var nMode = CreateXmlDOM().createAttribute("navigationMode");            
        nMode.value = navigationMode.value;
        
        item.xml.attributes.setNamedItem(nMode);
        array.push(item);
    }
        
}

function OnClose()
{ 
    if (appPointer == null || appPointer.xmlSource == null)
        return false;
    
    if (!appPointer.finished)
    {
        if (strictControl)
        {
            appPointer.Finish(false);
        }
        else
        {
            var test = appPointer.xmlSource.getElementsByTagName("assessmentTest")[0];
            test.getElementsByTagName("timeLimits")[0].attributes.getNamedItem("maxTime").value = timerPointer.time;
            new ServerManager().DeleteUserAnswers(test);    
        }    
    }
    
    return true;    
}



var errorIsShown = false; // если уже показана ошибка, то зачем опять показывать сообщение об ошибке (ведь если чего то не так.. то логично, что ошибки ещё будут...)



// string error 
function ShowError(error)
{
    if (!errorIsShown)
    {        
        window.status = "error";                    
        var xmldom = CreateXmlDOM();
        var main = xmldom.createElement("main");        
        var errorNode = xmldom.createElement("error");
        var message = xmldom.createElement("message");
        var div = xmldom.createElement("div");        
        
        if (!isMozilla)
            div.text = error;   // если ошибка
        else
            div.textContent = error;   // если ошибка            
        
        message.appendChild(div);
        errorNode.appendChild(message);
        main.appendChild(errorNode);        
        document.body.innerHTML = TransformNode(errorNode, "xslt/ErrorTemplate.xsl");                
        //itemFasade.innerHTML = TransformNode(errorNode, "xslt/ErrorTemplate.xsl");                
        errorIsShown = true;
        HideWaitPanel();
        if (titleFasade != null)
            titleFasade.style.display = 'none';
    }    
    
}



// не позволяет менятся значению элемента управления
function notChange(event)
{
    var aEvent = event ? event : window.event;        
    var el = aEvent.srcElement ? aEvent.srcElement : aEvent.target;
    el.checked = !el.checked;
}


function timeToStr(secCount)
{                                        
    var hours = Math.floor(secCount / 3600);
    secCount = secCount % 3600;
    
    var mins = Math.floor(secCount / 60);
    secCount = secCount % 60;
    
    var secs = secCount;
    
    var str = "";                    
    if (hours > 0)
    {
        if (hours < 10)
            str = str + "0";
        str = str + hours + ":";   
    }
    if (mins > 0)                    
    {
        if (mins <10)
            str = str + "0";
        str = str + mins + ":"                            
    }           
    else
        if (hours > 0)
        {
            str = str + "00:";
        }
    if (secs < 10)         
        str = str + "0";
    str = str + secs;    
    return str;                                   
}


function divSectionChange()        // для репорта
{
    var divS = document.getElementById("divSection");
    var imgE = document.getElementById("imgE");
    if (divS.style.display == 'none')
    {
        divS.style.display = 'block';
        imgE.src="../Images/minus.gif"
    }
    else
    {
        divS.style.display = 'none';
        imgE.src="../Images/plus.gif"
    }            
}


function ShowWaitPanel(text, description)
{
    var tBodyWait = document.getElementById('tBodyWait');
    tBodyWait.style.display = "block";    
    document.getElementById("spanWaitTitle").innerHTML = text;
    document.getElementById("spanWaitDescription").innerHTML = description;    
}
function HideWaitPanel()
{
    var tBodyWait = document.getElementById('tBodyWait');
    tBodyWait.style.display = "none";
}


function ShowCloseButtons()
{
    var elements = document.getElementsByTagName('div');         
    for (var i = 0; i < elements.length; i++)
    {    
        if (elements[i].className == "CloseButton")
            elements[i].style.display = "block";
    }
}


function GetDirectChildNodes(node, childName)
{   
    var children = []
    
    if (!isMozilla)
    {
       children = node.selectNodes(childName);
    }        
    else
    {       
       var allChildren = node.getElementsByTagName(childName);
       
       for (var i = 0; i < allChildren.length; i++)
       {           
           if (allChildren.item(i).parentNode == node)
                children.push(allChildren.item(i));
       }
    }
    return children;
}